package com.wjy.filter;

import com.wjy.response.ResponseBuilder;
import com.wjy.thread.ThreadLocalEnv;
import com.wjy.thread.ThreadLocalVar;
import com.wjy.util.TokenUtil;
import lombok.extern.log4j.Log4j2;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/**
 * @author ybxxszl
 * @date 2018年10月9日
 * @description 请求过滤
 */
@Log4j2
@Provider
public class RequestFilter implements ContainerRequestFilter {

    private static Set<String> ignore = new HashSet<String>();

    // 忽略验证
    static {

        ignore.add("/wechat/author/loginAuthor");
        ignore.add("/wechat/author/registerAuthor");
        ignore.add("/wechat/author/sendVerifyCode");

        ignore.add("/swagger.json");

    }

    // 添加忽略验证
    public static void add(String p) {

        ignore.add(p);

    }

    public void lookIgnoreVerifyInfo(String path) {

        if (path.startsWith("/swagger.json")) {

            log.info("Swagger API");

        } else {

            log.info("IGNORE: " + path);

        }

    }

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

        String path = requestContext.getUriInfo().getPath();

        log.warn("请求路径：" + path);

        String authorId = requestContext.getHeaderString("H-AuthorId");

        String token = requestContext.getHeaderString("H-Token");

        log.warn("H-AuthorId: " + authorId + " H-Token: " + token);

        Boolean verify = true;

        for (String str : ignore) {

            if (path.contains(str)) {

                lookIgnoreVerifyInfo(path);

                verify = false;

            }

        }

        if (verify) {

            if (token == null || !TokenUtil.verifyToken(token)) {

                requestContext.abortWith(ResponseBuilder.error("请重新登录"));

            } else {

                ThreadLocalVar threadLocalVar = new ThreadLocalVar();

                threadLocalVar.setToken(token);

                if (authorId != null) {

                    threadLocalVar.setAuthor_id(authorId);

                }

                ThreadLocalEnv.setENV(threadLocalVar);

            }

        } else {

            ThreadLocalVar threadLocalVar = new ThreadLocalVar("unAuthorId", "unToken");

            ThreadLocalEnv.setENV(threadLocalVar);

        }

    }

}
